package com.viser.komercijala.http;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.Vector;

public class HttpDispatcher implements IHttpDispatcher {

	@Override
	public String getHttpResponse_GET(String url) throws Exception{
		String webpage = "";
        BufferedReader reader=null;
        try
        {
        reader = new BufferedReader(new InputStreamReader(new URL(url).openStream()));
        String line = reader.readLine();
        while (line != null) {
                webpage = webpage + /*"\n" +*/ line;
                line = reader.readLine();
        }
        }catch(Exception ex){ex.printStackTrace(); return "#error: "+ex.getMessage();}
        return webpage.trim();
	}

	@Override
	public String getHttpResponse_POST(String url, Vector<String> postParameters) throws Exception{
		try { 
			// Construct data 
			String data = preparePOSTData(postParameters); 
			
			// Send data 
			URL urlObject = new URL(url); 
			URLConnection conn = urlObject.openConnection(); 
			conn.setDoOutput(true); 
			OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); 
			wr.write(data); wr.flush(); 
			// Get the response 
			BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); 
			String line; 
			String returnString="";
			while ((line = rd.readLine()) != null) 
			{ 
				// Process line... 
				returnString+=/*"\n"+*/line;
			} 
			wr.close(); 
			rd.close(); 
			return returnString.trim();
		} catch (Exception e) {return "#error: "+e.getMessage(); }
	}

	@Override
	public String preparePOSTData(Vector<String> data) throws Exception{
		String postData="";
		for(String parameter : data)
		{
			String[] pair = parameter.split("=");
			if(pair.length<2)throw new Exception("HttpDispatcher: Unable to parse string{"+
					parameter+"}as http parameter!");
			String key=pair[0]; String val=pair[1];
			if(postData.length()>0)postData+="&";
			postData+=URLEncoder.encode(key, "UTF-8")+"="+URLEncoder.encode(val, "UTF-8");
		}
		return postData;
	}

}
